<template>
  <div v-loading="loading" class="organization-main">
    <!--menu start-->
    <div class="menu-container">
      <div class="menu-content">
        <el-scrollbar style="height:100%" class="app-hid-scrollbar-x">
          <div
            v-for="(v,k) in roleList"
            :key="k"
            class="menu-item pointer"
            :data-menu="v.id"
            :class="{'is-active':activeRole&&activeRole.id===v.id}"
            @click="handleCheckRole(v)"
          >{{ v.name }}
          </div>
        </el-scrollbar>
      </div>
    </div>
    <!--menu end-->

    <!--list start-->
    <div class="rules-container">
      <div v-if="!activeRole" class="empty-tips">
        <div>请先新增角色</div>
        <br>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          round
          class="btn-tree"
          @click="handleEditRole('add')"
        >新增角色
        </el-button>
      </div>

      <div v-else>
        <div class="rules-title flex-x-between-center">
          <div>当前角色：<span class="role-name">{{ activeRole.name }}</span></div>
          <div>
            <el-button type="primary" size="small" round class="btn-tree" @click="handleEditRole('add')">新增角色
            </el-button>
            <el-button type="primary" size="small" round @click="handleEditRole('edit',activeRole)">编辑角色</el-button>
            <el-button type="danger" size="small" round @click="handleDelRole">删除角色</el-button>
          </div>
        </div>
        <div class="perm-container">
          <el-form ref="form" label-width="150px" size="small" label-position="left">
            <div class="perm-content">
              <el-scrollbar style="height:100%" class="app-hid-scrollbar-x">
                <div>
                  <el-scrollbar style="height:100%" class="hid-scrollbar-x">
                    <el-form-item class="perm-title" label="操作对象">
                      <div class="flex-x-between-center">
                        <span class="check-left perm-title-value">权限</span>
                        <div class="check-right">
                          <el-checkbox
                            v-model="allPermission"
                            @change="allPermCheckedChange"
                          >全部权限
                          </el-checkbox>
                        </div>
                      </div>
                    </el-form-item>
                    <el-form-item
                      v-for="(group,index) in groupList"
                      :key="group.groupId"
                      :label="group.groupName"
                    >
                      <div class="flex-x-between-center">
                        <div class="check-left">
                          <div class="check-group">
                            <el-checkbox
                              v-for="perm in group.permInfos"
                              :key="perm.id"
                              v-model="permList"
                              class="check-item"
                              :disabled="allPermission"
                              :label="perm.id"
                            >{{ perm.name }}
                            </el-checkbox>
                          </div>
                        </div>
                        <div class="check-right">
                          <el-button
                            :disabled="allPermission"
                            type="text"
                            size="small"
                            @click="currentAllPermChecked[index].checked=true;currentAllPermCheckedChange(index)"
                          >
                            全选
                          </el-button>
                          <el-button
                            :disabled="allPermission"
                            type="text"
                            size="small"
                            @click="currentAllPermChecked[index].checked=false;currentAllPermCheckedChange(index)"
                          >
                            取消全选
                          </el-button>
                        </div>
                      </div>
                    </el-form-item>

                  </el-scrollbar>
                </div>
              </el-scrollbar>
            </div>

            <el-form-item style="padding: 0 10px">
              <el-button size="small" round type="primary" @click="handleSubmitRules">保 存</el-button>
              <el-button size="small" round @click="handleResetRules">重 置</el-button>
            </el-form-item>
          </el-form>

        </div>
      </div>

    </div>
    <!--list end-->

    <!--组件-->
    <DialogEditRole ref="dialogEditRole" />
  </div>
</template>

<script>
import DialogEditRole from './DialogEditRole'
import { roleList, delRole, rolePerms, updateRolePerms } from '@/api/user/role'

export default {
  components: {
    DialogEditRole
  },
  data() {
    return {
      // 配置
      // 状态
      loading: false,
      // 数据
      roleList: [],
      activeRole: null,
      allPermission: null, // 是否所有全选
      permList: [], //  当前选择
      tempPermList: [], // 不是全选状态选择
      groupList: [], // 所有权限选项
      allPermList: [], // 所有权限选项id集合
      currentAllPermChecked: []
    }
  },
  computed: {},
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    this.fetchData()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 初始化
    fetchData() {
      this.loading = true
      roleList().then(res => {
        const roleList = res.data || []
        this.roleList = roleList
        // 判断是否有原来激活角色
        if (roleList.length) {
          if (this.activeRole) {
            const flag = roleList.some(v => {
              if (v.id === this.activeRole.id) {
                this.activeRole = v
                return true
              }
            })
            if (!flag) this.activeRole = null
          } else {
            this.activeRole = roleList[0]
          }
          this.getRolePerms()
        } else {
          this.activeRole = null
        }
      }).finally(() => {
        this.loading = false
      })
    },

    // 获取role权限
    getRolePerms() {
      if (!this.activeRole) return
      this.loading = true
      this.currentAllPermChecked = []
      rolePerms({ params: { roleId: this.activeRole.id } }).then(res => {
        this.permList = res.data.permList
        const groupList = res.data.groupPermInfos || []
        this.allPermission = res.data.allPermission
        let allPermList = []
        for (const group in groupList) {
          const permInfos = groupList[group].permInfos
          const ids = permInfos.map(item => item.id)
          allPermList = allPermList.concat(ids)
          this.currentAllPermChecked.push({ checked: false, ids: ids })
        }
        this.groupList = groupList
        this.allPermList = allPermList
        if (this.allPermission) {
          this.tempPermList = this.permList
          this.permList = allPermList
        }
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 按钮组
     */
    // 新增 编辑role
    handleEditRole(mode = 'add', row = null) {
      this.$refs.dialogEditRole.open({ mode, row }).then(() => {
        this.fetchData()
      })
    },

    // 选择role
    handleCheckRole(role) {
      this.activeRole = role
      this.getRolePerms()
    },

    // 删除role
    handleDelRole() {
      this.$confirm(
        `确定删除角色：${this.activeRole.name} ?`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          const params = { roleId: this.activeRole.id }
          this.loading = true
          delRole({ params })
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.activeRole = null
              this.fetchData()
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
        })
    },

    // 保存rules
    handleSubmitRules() {
      const params = {
        id: this.activeRole.id,
        allPermission: this.allPermission,
        permList: this.permList
      }
      this.loading = true
      updateRolePerms({ data: params }).then(res => {
        this.$notify({
          title: '成功',
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
      }).finally(() => {
        this.loading = false
      })
    },

    // 重置rules
    handleResetRules() {
      this.getRolePerms()
    },

    /**
     * 状态组
     */
    // 全部权限
    allPermCheckedChange() {
      if (this.allPermission) {
        this.tempPermList = this.permList
        this.permList = this.allPermList
      } else {
        this.permList = this.tempPermList
      }
    },

    // 每一项权限全选
    currentAllPermCheckedChange(index) {
      const flag = this.currentAllPermChecked[index].checked
      const ids = this.currentAllPermChecked[index].ids
      if (flag) {
        this.permList = [...new Set(this.permList.concat(ids))]
      } else {
        const a = this.permList
        const b = ids
        const c = []
        a.forEach(v => {
          if (b.indexOf(v) === -1) c.push(v)
        })
        this.permList = c
      }
    }
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.organization-main {
  display: flex;

  /*菜单容器*/
  .menu-container {
    flex: 0 0 auto;
    height: 100%;

    padding-right: 10px;
    text-align: center;
    border-right: 1px solid #EBEEF5;

    .menu-content {
      height: calc(100vh - 155px);
    }

    .menu-item {
      height: 36px;
      margin-bottom: 10px;
      padding: 0 20px;
      line-height: 36px;
      font-size: 14px;
      color: #303133;
      border-radius: 10px;

      &:not(.is-active) {
        &:hover {
          background-color: #F5F7FA;
        }
      }
    }

    .is-active {
      color: $primary;
      background-color: #eef4fe;
    }
  }

  /*权限*/
  .rules-container {
    flex: 1 1 auto;
    padding-left: 10px;

    .empty-tips {
      text-align: center;
      font-size: 12px;
      padding-top: 100px;
    }

    .rules-title {
      line-height: 40px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .role-name {
      color: $primary
    }

    .perm-container {
      .perm-content {
        height: calc(100vh - 240px);
      }
    }

    .perm-title {
      padding-bottom: 0 !important;
    }

    .perm-title-value {
      color: #999 !important;
    }

    .el-form-item {
      margin-bottom: 0;
      padding: 10px 10px 10px 10px;
      border-bottom: 1px solid #e7e7e7;
    }

    .el-form-item:last-child {
      border-bottom: none;
    }

    //.el-form-item /deep/ .el-form-item__label {
    //  color: #333 !important;
    //  font-weight: normal;
    //}
    //
    //.perm-title /deep/ .el-form-item__label {
    //  color: #999 !important;
    //}
    //
    //.el-form-item /deep/ .el-checkbox__label {
    //  color: #666;
    //}

    // .el-checkbox-group {
    .el-checkbox,
    .el-checkbox + .el-checkbox {
      margin-left: 0;
      margin-right: 20px;
    }

    // }

    .check-group {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
    }

    .check-left {
      flex: 1 1 auto;

      .el-checkbox {
        margin-left: 0;
        margin-right: 20px;
      }
    }

    .check-right {
      display: flex;
      flex: 0 0 auto;
      width: 100px;

      .el-checkbox {
        margin-left: 0;
        margin-right: 0;
      }
    }

    .check-item {
      min-width: 160px;
    }
  }
}

</style>
